<template>
  <div id="demo-container"></div>
</template>

<script setup name="MyDemo">
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import model from "@/assets/mesh/guandao1.gltf";
import { onMounted } from "vue";

onMounted(() => {
  const demoContainer = document.getElementById("demo-container");
  // 创建3D场景对象Scene
  const scene = new THREE.Scene();

  // #cee5ed 淡蓝色 #1f1f1f 黑色
  scene.background = new THREE.Color().setStyle("#1f1f1f"); // 例如，设置为灰色
  // scene.fog = new THREE.Fog(0xaaaaaa, 1, 100); // 颜色, 起始距离, 结束距离

  // 创建GLTF加载器对象
  const loader = new GLTFLoader();

  // AxesHelper：辅助观察的坐标系
  // const axesHelper = new THREE.AxesHelper(150);
  // scene.add(axesHelper);

  const directionalLight = new THREE.DirectionalLight(0xffffff, 1.0);
  directionalLight.position.set(0, 0, 100);
  scene.add(directionalLight);

  const directionalLight2 = new THREE.DirectionalLight(0xffffff, 1.0);
  directionalLight2.position.set(0, 100, 40);
  scene.add(directionalLight2);

  // const pointLight = new THREE.PointLight(0xffffff, 1.0);
  // pointLight.position.set(100, 100, 100);
  // scene.add(pointLight);

  const width = window.screen.width;
  const height = window.screen.height;
  const camera = new THREE.PerspectiveCamera(30, width / height, 1, 3000);
  camera.position.set(460, 480, 460);
  camera.lookAt(0, 0, 0); //指向mesh对应的位置

  const renderer = new THREE.WebGLRenderer();
  renderer.setSize(width, height);
  renderer.render(scene, camera);
  demoContainer.appendChild(renderer.domElement);

  loader.load(model, function (gltf) {
    console.log(gltf);
    scene.add(gltf.scene);
    // 文档加载是一个异步的过程，所以文档加载完成要渲染一次，否则视图中是看不到物体的。
    renderer.render(scene, camera);
    demoContainer.appendChild(renderer.domElement);
  });

  // 设置相机控件轨道控制器OrbitControls
  const controls = new OrbitControls(camera, renderer.domElement);
  // 如果OrbitControls改变了相机参数，重新调用渲染器渲染三维场景
  controls.addEventListener("change", function () {
    renderer.render(scene, camera); //执行渲染操作 // 上面如果用了动画帧，那么相机控件这里就不要再执行对于的渲染了
  }); //监听鼠标、键盘事件
});
</script>

<style scoped>
#demo-container {
  width: 100%;
  height: 100%;
}
</style>
